#pragma once
#include"Common.hpp"

class InetAddr
{
public:
    // 网络系列转主机系列
    InetAddr(const struct sockaddr_in &addr)
    {
       SetAddr(addr);
    }

    InetAddr()
    {
    }

    InetAddr(int port)
        : _ip("0.0.0.0"),
          _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;
    }

    // 主机系列转网络系列
    InetAddr(const std::string& ip, int port)
        : _ip(ip),
          _port(port)
    {
        memset(&_addr, 0, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
    }

    uint16_t Port()
    {
        return _port;
    }

    std::string StringAddr()
    {
        return _ip + ":" + std::to_string(_port);
    }

    const struct sockaddr_in &GetAddr()
    {
        return _addr;
    }

    sockaddr* GetSockaddr()
    {
        return (sockaddr*)&_addr;
    }

    int Getlen()
    {
        return sizeof(_addr);
    }


    bool operator==(InetAddr &peer)
    {
        return _ip == peer._ip && _port == peer._port;
    }


    void SetAddr(const struct sockaddr_in& addr)
    {
        _addr=addr;
        _port = ntohs(_addr.sin_port);
        //_ip = inet_ntoa(_addr.sin_addr);
        char buffer[64];
        inet_ntop(AF_INET, &addr.sin_addr, buffer, sizeof(_addr));
        _ip = buffer;
    }



private:
    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
};